package com.codegen;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DatabaseMetaReader {
    private static final String SQL_TABLE_COLUMNS = 
        "SELECT COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT, COLUMN_KEY " +
        "FROM INFORMATION_SCHEMA.COLUMNS " +
        "WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?";

    public List<TableMeta> readDatabaseMeta(String dbName, String url, String userName, String password) throws SQLException {
        try (Connection conn = DriverManager.getConnection(url, userName, password)) {
            List<String> tableNames = getTableNames(conn, dbName);
            List<TableMeta> tableMetas = new ArrayList<>();
            for (String tableName : tableNames) {
                tableMetas.add(readTableMeta(conn, dbName, tableName));
            }
            return tableMetas;
        }
    }

    private List<String> getTableNames(Connection conn, String dbName) throws SQLException {
        List<String> tableNames = new ArrayList<>();
        DatabaseMetaData metaData = conn.getMetaData();
        
        try (ResultSet tables = metaData.getTables(dbName, null, null, new String[]{"TABLE"})) {
            while (tables.next()) {
                tableNames.add(tables.getString("TABLE_NAME"));
            }
        }
        return tableNames;
    }

    private TableMeta readTableMeta(Connection conn, String dbName, String tableName) throws SQLException {
        TableMeta table = new TableMeta();
        table.setName(tableName);
        table.setComment(getTableComment(conn, tableName));
        
        try (PreparedStatement ps = conn.prepareStatement(SQL_TABLE_COLUMNS)) {
            ps.setString(1, dbName);
            ps.setString(2, tableName);
            ResultSet rs = ps.executeQuery();
            
            List<ColumnMeta> columns = new ArrayList<>();
            while (rs.next()) {
                ColumnMeta col = new ColumnMeta();
                col.setName(rs.getString("COLUMN_NAME"));
                col.setType(rs.getString("DATA_TYPE"));
                col.setComment(rs.getString("COLUMN_COMMENT"));
                col.setPrimary("PRI".equals(rs.getString("COLUMN_KEY")));
                columns.add(col);
            }
            table.setColumns(columns);
        }
        return table;
    }
    
    private String getTableComment(Connection conn, String tableName) throws SQLException {
        // 简化实现，实际项目中应从元数据获取
        return tableName + "表";
    }
}